<?php
namespace app\modules\cruise\controllers;

use Yii;
use app\modules\cruise\models\Cruise;
use app\modules\cruise\models\RoomCode;
use app\modules\cruise\models\RoomUse;
use app\modules\cruise\models\RoomCodeUse;
use app\modules\cruise\models\Customer;

use yii\web\UploadedFile;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\Pagination;
use yii\data\ArrayDataProvider;
use yii\data\Sort;



class DeckController extends Controller
{

    public function behaviors()
    {
		return [
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'delete' => ['post'],
				],
			],
             'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        //'actions' => ['list', 'index','create','view','update','delete'],
                        'roles' => ['@'],
                    ],
                ],
            ],
			
		];
    }


    //甲板分配房间号
    public function actionIndex($cruise_id){
    	if(empty($cruise_id)){
    		return false;
    	}
    	$model = Cruise::findOne($cruise_id);//邮轮

    	$deck = []; //甲板层
    	if(isset(yii::$app->params['deck'][$model->id])){
    		$deck = yii::$app->params['deck'][$model->id];
    	}else{
            header('Content-type:text/html;charset=utf-8');
            exit("没有导入甲板层！无法分房");
        }

        $color = []; //房型代码颜色

        $colors = RoomCode::find()->where(['cruise_id'=>$model->id])->groupBy('type_code')->all();
        
        $room_type = RoomCode::find()->where(['cruise_id'=>$model->id])->groupBy('type')->all();
       
        $color = $colors;
        
        //该船期下 导入的房间号
        $import_code = [];
        $import_codes = RoomCodeUse::find()->where(['cruise_id'=>$model->id])->all();

        if($import_codes){
            $import_code = \yii\helpers\ArrayHelper::map($import_codes, 'id', 'code');
        }
       
    	//获得已经分配的房间号
        $ready_code = RoomUse::find()->where(['status'=>1])->andWhere(['not', ['code' => null]])->all();
        $exit_code = \yii\helpers\ArrayHelper::map($ready_code, 'id', 'code');


    	return $this->render('index',['model'=>$model,'deck'=>$deck,'exit_code'=>$exit_code,'import_code'=>$import_code,'color'=>$color,'room_type'=>$room_type]);
    }

    //ajax 请求数据
    public function actionGetRoom(){
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $data = \yii::$app->request->get();
        $pageNum = isset($data['pageNum']) ? $data['pageNum'] : 1;
        
        $room_status = isset($data['room_status']) ? $data['room_status'] : 0;
        
        $room_t = isset($data['room_t']) ? $data['room_t'] : 0;
        $supply = isset($data['supply']) ? $data['supply'] : 0;
        $group = isset($data['group']) ? $data['group'] : 0;
        $name = isset($data['name']) ? $data['name'] : '';

        $data = [];
        
        $pageSize = 10;

        $query = RoomUse::find()->joinWith(['searchCustomer'])->where(['room_use.status'=>1]);
        if($room_status){
           
            if($room_status == 1){
                $query->andWhere(['or',['code'=>' '],['code'=>null]]);
            }elseif($room_status == 2){
                $query->andWhere(['not',['code' => null]]); 
                $query->andWhere(['not',['code' => ' ']]);
            }
        }

        if($name){
            $query->andWhere(['like','customer.name',$name]);
        }

        if($room_t || $supply || $group){
            $cusquery = Customer::find()->where(['status'=>1]);
            if($room_t){
                if($room_t == 'none'){
                    $cusquery->andWhere(['room_id'=>0]);
                }else{
                    $cusquery->andWhere(['room_id'=>$room_t]);
                }
            }

            if($supply){
                if($supply == 'none'){
                    $cusquery->andWhere(['or',['supply'=>' '],['supply'=>null]]);
                }else{
                    $cusquery->andWhere(['supply'=>$supply]);
                }
            }

            if($group){
                if($group == 'none'){
                    $cusquery->andWhere(['or',['group'=>' '],['group'=>null]]);
                }else{
                    $cusquery->andWhere(['group'=>$group]);
                }
            }

            

            $cus_model = $cusquery->all();
            $ids = [];
            if($cus_model){
               foreach($cus_model as $cum){
                $ids[] = $cum->room_use_id;
               } 
            }

           

            $query->andWhere(['room_use.id' => $ids]);
        }
           
      

        $totalItem = $query->count();
        $totalPage = ceil($totalItem/$pageSize);
        $startItem = ($pageNum-1) * $pageSize;
        $res['totalItem'] = $totalItem;
        $res['pageSize'] = $pageSize;
        $res['totalPage'] = $totalPage;
        $allRoom = $query->offset($startItem)->limit($pageSize)->all();
        
        if($allRoom){
            foreach($allRoom as $k=>$room){
                $data[$k]['id'] = $room->id;
                $data[$k]['type'] = $room->room->type;
                $data[$k]['type_code'] = $room->room->code;
                $data[$k]['num'] = $room->num;
                $data[$k]['num2'] = $room->customerNum;
                $data[$k]['code'] = ($room->code) ? ($room->code) :0;
                $data[$k]['name'] = $room->room->name.$room->room->code. $room->num.'人间';
                $data[$k]['remark'] = $room->remark;
                $customers = [];
                if($room->customer){
                    foreach($room->customer as $k2=>$c){
                        if($c->status == 1){
                            $customers[$k2]['name']= $c->first_name.$c->last_name;
                            $customers[$k2]['remark']= $c->remark; 
                            $customers[$k2]['group']= $c->group;
                            $customers[$k2]['supply']= $c->supply;
                        }
                    }   
                }
                $data[$k]['customers'] = $customers;   
            }    
        }

        $res['data_content'] = $data;
        return $res;
    }

    //ajax 房间具体信息
    public function actionDetailRoom(){
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $data = \yii::$app->request->get();
        $res = ['code'=>0,'msg'=>'error'];
        if(isset($data['rc_id']) && $data['rc_id']){
            $id = $data['rc_id'];
            $model = RoomCode::findOne($id);
            if($model){
                $RoomUse = RoomUse::find()->where(['code'=>$model->code])->one();
                $res['code'] = 1;
                $res['name'] = $model->cruise->name;
                $res['deck'] = $model->deck;
                $res['room_code'] = $model->code;
                $res['bed'] = $model->bed;
                $res['type'] = \yii::$app->params['room_type'][$model->type];
                $res['type_code'] = $model->type_code;
                $res['num'] = $model->num ? $model->num.'人' : '';
                if($RoomUse){
                    $res['num2'] = $RoomUse->customerNum.'人';
                    $str = '';
                    if($RoomUse->customer){
                        foreach($RoomUse->customer as $k2=>$c){
                            if($c->status == 1){
                              $str .= $c->first_name.$c->last_name.' ';
                            }
                        }   
                    }
                    $res['username'] = $str;
                }else{
                    $res['num2'] = '';
                    $res['username'] = '';
                }
                return $res;
            }
            return $res;
        }
        return $res;
    }

    //房间详情
    public function actionRoomCode($rc_id,$cruise_id){
        $this->layout = false;

        if(empty($rc_id)){
             return false;
        }
        $model = RoomCode::findOne($rc_id);

        $rcp = RoomCodeUse::find()->where(['room_code_id'=>$rc_id,'cruise_id'=>$cruise_id])->one();
       
        return $this->render("room-code",['model'=>$model,'rcp'=>$rcp]);
    }

    //分配房间号
    public function actionSetRoom($room_id,$code){

        if(!$room_id || !$code){
            return 0;
        }
        $model = RoomUse::findOne($room_id);
        if(!$model){
            return 0;
        }
      
        $rcp = RoomCodeUse::find()->where(['cruise_id'=>$model->room->cruise_id,'code'=>$code])->one();
        if($rcp){
            $rcp->is_use = 2;
            $rcp->save();
        }
        $model->code = $code;
        if($model->save()){
            return 1;
        }
        return 0;
    }

    //添加房间号
    public function actionCreateCode($cruise_id){
        $this->layout = '//empty';
        $model = new RoomCodeUse();
        if ($model->load(Yii::$app->request->post())) {
            $data = \yii::$app->request->post();
            if(isset($data['code']) && $data['code']){
               $code = $data['code'];
               $code = explode(";",$code);
               if(is_array($code)){
                  foreach($code as $c){
                      $room_code = RoomCode::find()->where(['cruise_id'=>$model->cruise_id,'code'=>$c])->one();
                      if($room_code){
                            $RoomCodeUse = new RoomCodeUse();
                            $RoomCodeUse->cruise_id = $model->cruise_id;
                            $RoomCodeUse->room_code_id = $room_code->id;
                            $RoomCodeUse->code = $c;
                            $RoomCodeUse->created_at = date("Y-m-d H:i:s");
                            $RoomCodeUse->save();
                      } 
                  }
                }  
            }
            return $this->redirect(Yii::$app->request->getReferrer());
        }else{
            $model->cruise_id = $cruise_id;
            return $this->render('create-code',['model'=>$model]);
        }    
       
    }

    //删除房间号
    public function actionDelRoom($rcp_id){
        if(empty($rcp_id)){
            return false;
        }
        $rcp = RoomCodeUse::findOne($rcp_id);
        if(empty($rcp)){
            return false;
        }
        //删除已分配的房号
        $model = RoomUse::find()->where(['code'=>$rcp->code])->one();
        if($model){
            $model->code = '';
            $model->save();
        }
        if($rcp->delete()){
            echo 1;
            exit();
        }

    }


    //清除房间号
    public function actionClearCode($room_id){
        if(!$room_id){
            return 0;
        }
        $model = RoomUse::findOne($room_id);

        if(!$model){
            return 0;
        }
        $rcp = RoomCodeUse::find()->where(['cruise_id'=>$model->room->cruise_id,'code'=>$model->code])->one();
        if($rcp){
            $rcp->is_use = 1;
            $rcp->save();
        }

        $model->code = '';
        if($model->save()){
            return 1;
        }
        return 0;
    }

    //down excel 
    public function actionDownExcel($id){
       
        if(empty($id)){
            return false;
        }
        $id = explode(',',$id);

        $orders = Order::find()->where(['id'=>$id])->all();

        $objPHPExcel = new \PHPExcel();
        $sheet = $objPHPExcel->getActiveSheet(0);
        $sheet->setTitle('房间号');
        $sheet->getDefaultStyle()->getFont()->setSize(9)->setName('微软雅黑');
        
        if(!empty($orders)){
            $key = 1;
            foreach($orders as $order){
                foreach($order->room as $room){
                    if($room->code){
                        $sheet->setCellValue(sprintf("A%d",$key),$room->code);
                        $key++;
                    }
                }
            }
        }    
        

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $fileName = sprintf("%s.xlsx",uniqid());
        $path = 'uploads/excel/'.date('Ym').'/';
        if(!is_dir($path)){  
              mkdir($path,0777,true);  
        }
        $file = $path.$fileName;
        $objWriter->save($file);
        
        $file_name = sprintf("%s.xlsx",'房间号表');
        header("Content-Type: application/force-download"); 
        header("Content-Type: application/octet-stream"); 
        header("Content-Type: application/download"); 
        header('Content-Disposition:inline;filename="'.$file_name.'"'); 
        header("Content-Transfer-Encoding: binary"); 
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
        header("Pragma: no-cache"); 
        $objWriter->save('php://output'); 
    }

    //excel 导入房间号
    public function actionImport(){

        $path = $this->upload_excel();
        if($path){
            $arrExcel = $this->getData($path);
            $data = yii::$app->request->post();
            if(!empty($data['cruise_id'])){
                
                $cruise_id = $data['cruise_id'];

                foreach($arrExcel as $line=>$arr){
                     $room_code = RoomCode::find()->where(['cruise_id'=>$cruise_id,'code'=>$arr['A']])->one();
                     if($room_code){
                        $RoomCodeUse = new RoomCodeUse();
                        $RoomCodeUse->cruise_id = $cruise_id;
                        $RoomCodeUse->room_code_id = $room_code->id;
                        $RoomCodeUse->code = $room_code->code;
                        $RoomCodeUse->created_at = date("Y-m-d H:i:s");
                        $RoomCodeUse->save();
                     } 
                }
            }
        }

        print_r(json_encode(['code'=>'ok','message'=>'导入成功!']));
    }

    //上传文件
    private function upload_excel(){

        $upload = UploadedFile::getInstanceByName('excel');
        if($upload){
            $suffix = $upload->extension;
            $dir = sprintf("uploads/excel/%s", date("Ym"));
             
            if(!is_readable($dir)) {
                is_file($dir) or mkdir($dir,0755);  
            }  

            $path = sprintf('%s/%s.%s', $dir, uniqid(true), $suffix);

            if($upload->saveAs($path)){
                return $path;
            }
        }else{
            return false;
        }

    }

    //excel获取数据
    private function getData($filePath){

        if(empty($filePath)){
            return [];
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($filePath)){
            $PHPReader = new \PHPExcel_Reader_Excel5();
        }
        if(!$PHPReader->canRead($filePath)){
            return ;
        }
        $PHPExcel = $PHPReader->load($filePath);

        /**读取excel文件中的第一个工作表*/
        $currentSheet = $PHPExcel->getSheet(0);

        /**取得最大的列号*/
        $allColumn = $currentSheet->getHighestColumn();

        /**取得一共有多少行*/
        $allRow = $currentSheet->getHighestRow();
        //return $allRow;
                    
        for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++){
            //for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
            for($colIndex='A';$colIndex<='A';$colIndex++){
                $addr = $colIndex.$rowIndex;
                $cell = $currentSheet->getCell($addr)->getValue();
                if($cell instanceof PHPExcel_RichText){     //富文本转换字符串
                    $cell = $cell->__toString();
                }
                if(!empty($cell)){
                    $str = str_replace(' ', '', $cell);
                    $arrExcel[$rowIndex][$colIndex]= $str;
                }
            }
        }
        return $arrExcel;
    }

}